#include "mpdef.h"
#include "mpnetclient.h"
#include "mpconfig.h"
#include "mpnet.h"
#include "mputils.h"

time_t CMpNetClient::ms_iLastFreeTime = 0;

void CMpNetClient::Init(CMpNet& stNet, SOCKET iSocket, int iMaxRunCount)
{
    CT_ASSERT(iSocket != INVALID_SOCKET);
    m_stSock.SetSocket(iSocket);
    m_pstNet = &stNet;

    // 注册到epoll
    int iRet = Register(
            stNet,
            &CMpNet::OnClientEvent, 
            m_pstNet->m_stEpoll,
            m_stSock.GetSocket(),
            EPOLLIN);
    CHECK_THROW(iRet);

    // 初始化缓冲区
    iRet = m_stRecvBuffer.Attach(NULL, CONF->ProcessRecvSize, 0);
    CHECK_THROW(iRet);

    iRet = m_stSendBuffer.Attach(NULL, CONF->ProcessSendSize, 0);
    CHECK_THROW(iRet);

    m_iMaxRumCount = iMaxRunCount;
}

void CMpNetClient::RecvOneCode(char*& pszCode, int& iCodeLen)
{
    CMpUtils::RecvOneCode(m_stSock, m_stRecvBuffer, pszCode, iCodeLen);
    m_pstNet->m_stStat.Put(mp_stat_recvpkg);
}

void CMpNetClient::RemoveOneCode(int iCodeLen)
{
    m_stRecvBuffer.Remove(iCodeLen);
}

void CMpNetClient::GetSendBuffer(char *&pszBuffer, int &iBufferLen)
{
    if (m_stSendBuffer.GetUsedLen() > 0)
    {
        CT_WARNING(("GetSendBuffer remain %d bytes", m_stSendBuffer.GetUsedLen()));
    }

    pszBuffer = m_stSendBuffer.GetFreeBuf() + sizeof(int);
    iBufferLen = m_stSendBuffer.GetFreeLen() - sizeof(int);
}

void CMpNetClient::SendOneCode(int iCodeLen)
{
    ++ m_iRunCount;

    if (m_stSendBuffer.GetUsedLen() > 0)
    {
        CT_WARNING(("m_stSendBuffer.GetUsedLen(%d)>0", m_stSendBuffer.GetUsedLen()));
    }

    *(int*)m_stSendBuffer.GetFreeBuf() = htonl(iCodeLen);
    m_stSendBuffer.Append(iCodeLen + sizeof(int));

    int iSendLen = 0;
    int iRet = m_stSock.Send(m_stSendBuffer.GetUsedBuf(),
        m_stSendBuffer.GetUsedLen(), iSendLen);
    CHECK_THROW(iRet);

    m_pstNet->m_stStat.Put(mp_stat_sendpkg);

    m_stSendBuffer.Remove(iSendLen);
}

bool CMpNetClient::IsReachMaxRunCount()
{
    return (m_iRunCount >= m_iMaxRumCount);
}
